import { Injectable } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { MenuItem } from '../models/left-menu-item';
import { BehaviorSubject } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class SearchNameService {
    constructor(private sanitizer: DomSanitizer) {}

    // 标记导航数据
    private navDatas = new BehaviorSubject<MenuItem[]>([]);

    private filterDatas = new BehaviorSubject<MenuItem[]>([]);

    private ORDER_REGEX = /^(\d+).\s/;

    /** 01. 说明文字
     * 经过转化后变成
     * 说明文字 */
    getRealName(orderedName): string {
        return orderedName.replace(this.ORDER_REGEX, '');
    }

    /** 标黄 */
    getHighlightedForLeftMenuName(orderedName, searchText): SafeHtml {
        const text = this.getRealName(orderedName);
        if (!searchText) return text;

        const highlightedText = text.replace(new RegExp(`(${searchText})`, 'ig'), '<span style="color:#f05b41">$1</span>');

        return this.sanitizer.bypassSecurityTrustHtml(highlightedText);
    }

    /** 排序 */
    sortNames(name1, name2): number {
        const redix = 10;
        return Number.parseInt(name1, redix) - Number.parseInt(name2, redix);
    }

    getNavDatas() {
        return this.navDatas;
    }

    /**
     * 用于 rapid-settings 传递已归集的变量数据
     */
    updateNavDatas(datas: MenuItem[]) {
        this.navDatas.next(datas);
    }

    getFilterDatas() {
        return this.filterDatas;
    }

    /**
     * 用于 search-name 传递过滤的数据
     * @param datas
     */
    updateFilterDatas(datas: MenuItem[]) {
        this.filterDatas.next(datas);
    }
}
